package com.sfx.concurrent.demo.OtherCoding;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-05-14
 * Time: 14:40
 */
public class Code_calculate2 {
    static class Solution {
        private int i = 0;
        public int calculate(String s) {
            Stack<Integer> stack = new Stack<>();
            char sign = '+';//记录前一个操作符
            int digit = 0;
            for (; i < s.length(); ++i) {
                char c = s.charAt(i);
                //是数字
                if (Character.isDigit(c)) {
                    digit = digit * 10 + (c - '0');
                }
                if (c == '(') {
                    i++;
                    digit = calculate(s);
                }
                if (!Character.isDigit(c) && c != ' ' || i == s.length() - 1) {
                    switch (sign) {
                        case '+':
                            stack.push(digit);
                            break;
                        case '-':
                            stack.push(-digit);
                            break;
                        case '*':
                            stack.push(stack.pop() * digit);
                            break;
                        case '/':
                            stack.push(stack.pop() / digit);
                            break;
                        default:
                            break;
                    }
                    sign = c;
                    digit = 0;
                }
                if (c == ')') {
                    break;
                }
            }
            int res = 0;
            while (!stack.isEmpty()) {
                res += stack.pop();
            }
            return res;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.calculate("2*(5+5*2)/3+(6/2+8)");
    }
}
